import { useState, useEffect } from 'preact/hooks'
import KnowledgeGraph from './components/KnowledgeGraph'
import ControlPanel from './components/ControlPanel'
import RecommendationPanel from './components/RecommendationPanel'

export function App() {
  const [graphData, setGraphData] = useState({ nodes: [], links: [] })
  const [recommendations, setRecommendations] = useState([])
  const [isProcessing, setIsProcessing] = useState(false)
  const [statusMessage, setStatusMessage] = useState('')

  useEffect(() => {
    // 加载初始图谱数据
    loadInitialData()
  }, [])

  const loadInitialData = async () => {
    try {
      const response = await fetch('/api/graph')
      const data = await response.json()

      // 转换数据格式为 force-graph 格式
      const nodes = data.nodes.map(node => ({
        id: node.id,
        name: node.label,
        type: node.type,
        color: node.color || '#4ECDC4',
        cluster: node.cluster,
        val: 1,
      }))

      const links = data.edges.map(edge => ({
        source: edge.source,
        target: edge.target,
        type: edge.type,
        color: edge.cross_domain ? '#FF00FF' : 'rgba(255,255,255,0.2)',
      }))

      setGraphData({ nodes, links })
    } catch (error) {
      console.error('加载数据失败:', error)
    }
  }

  return (
    <div class="w-full h-full relative">
      {/* 标题栏 */}
      <div class="absolute top-0 left-0 right-0 z-10 bg-gradient-to-b from-dark to-transparent p-6">
        <h1 class="text-3xl font-bold text-center bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent">
          知识图谱推荐系统
        </h1>
        {statusMessage && (
          <p class="text-center mt-2 text-sm text-gray-300 fade-in">
            {statusMessage}
          </p>
        )}
      </div>

      {/* 3D知识图谱 */}
      <KnowledgeGraph
        graphData={graphData}
        setGraphData={setGraphData}
        recommendations={recommendations}
      />

      {/* 左侧控制面板 */}
      <ControlPanel
        setGraphData={setGraphData}
        setRecommendations={setRecommendations}
        setIsProcessing={setIsProcessing}
        setStatusMessage={setStatusMessage}
        isProcessing={isProcessing}
      />

      {/* 右侧推荐面板 */}
      <RecommendationPanel
        recommendations={recommendations}
        isProcessing={isProcessing}
      />

      {/* 加载指示器 */}
      {isProcessing && (
        <div class="absolute bottom-8 left-1/2 transform -translate-x-1/2 z-20">
          <div class="bg-dark/90 backdrop-blur-sm px-6 py-3 rounded-full border border-primary/30 flex items-center gap-3">
            <div class="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
            <span class="text-sm text-primary">处理中...</span>
          </div>
        </div>
      )}
    </div>
  )
}
